//
//  NEADViewModel.m
//  NetEasyNews
//
//  Created by weiwang on 16/7/17.
//  Copyright © 2016年 王伟. All rights reserved.
//

#import "NEADViewModel.h"
#import <AFNetworking/AFNetworking.h>
#import "NENetWorkManager.h"
#import "NEADEntity.h"
#import "NEADDataEntity.h"


@implementation NEADViewModel


- (instancetype) init
{
    if (self = [super init])
    {
        [self setupRACCommand];
    }
    
    return self;
}

- (void)setupRACCommand
{
    @weakify(self);
    _fetchADCommand = [[RACCommand alloc]initWithSignalBlock:^RACSignal *(id input) {
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
            @strongify(self);
            [self requestForADSuccess:^(NSDictionary *result) {
                NEADEntity *entity = [NEADEntity mj_objectWithKeyValues:result];
                NSLog(@"%@", entity);
                //序列华
                dispatch_async(dispatch_queue_create("com.oneway.archiveData", nil), ^(void){
                    [entity archive];
                });
                [subscriber sendNext:entity];

            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                [subscriber sendError:error];
            }];
            return nil;
        }];
    }];
}

- (void)requestForADSuccess:(void (^)(NSDictionary *result))success
                    failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
{
     NSInteger now = [[[NSDate alloc] init] timeIntervalSince1970];
    NSString *path = [NSString stringWithFormat:@"http://g1.163.com/madr?app=7A16FBB6&platform=ios&category=startup&location=1&timestamp=%ld",(long)now];
    
    [[NENetWorkManager sharedInstance] GET:path parameters:nil success:^(NSURLSessionDataTask *task, id resonse){
        success(resonse);
       
        
    }failure:^(NSURLSessionDataTask *task, NSError *error){
        failure(task, error);
    }];

}
@end
